var core = require('core');
var wechat = core.wechat;
var send = core.send;
var sign = require('../admin/sign');
var step = core.step;

var GET = function(req, res, next){
    var query = req.query;
    var state = query.state ? JSON.parse(query.state) : query.state;
    var status = query.status;
    var token = query.token ? query.token : ( state ? state.token : null );
    var mid = query.mid ? query.mid : ( state ? state.mid : null );
    var ooid = query.oid ? query.oid : ( state ? state.ooid : null );
    var errcode = query.errcode;
    var code = query.code;

    if(!state && mid && token && ooid && !status && !code && !errcode){
        core.api("open/getToken", {token: token, type: "TempToken"}, function(err, body){
            if(err || !body.docs || body.code || body.docs.data)
                return res.render('admin/error', {msg: "token失效", docs: {
                    jssdk: wechat.getJSSDK(req.originalUrl)
                }});
            else{
                return res.redirect("https://open.weixin.qq.com/connect/oauth2/authorize?appid="+ wechat.config.AppID +"&redirect_uri="+ wechat.config.URL+"open/merchant_admin_create&response_type=code&scope=snsapi_base&state="+(
                    JSON.stringify({
                        token : token,
                        ooid : ooid,
                        mid : mid
                    })
                )+"#wechat_redirect");
            }
        });
    }else if(state && code && token && ooid && mid && !status && !errcode){
        var param = {
            appid : wechat.config.AppID,
            secret : wechat.config.AppSecret,
            code : code,
            grant_type : 'authorization_code'
        };
        wechat.api.get('sns/oauth2/access_token', param, function(err, body){
            if(err || errcode)
                return res.render('admin/error', {msg: "微信认证失败", docs: {
                    jssdk: wechat.getJSSDK(req.originalUrl)
                }});
            else{
                core.api('open/upToken', { token: token, type: "TempToken", data: JSON.stringify({oid: body.openid, ooid: ooid, type: 1, mid : mid}) }, function(err, body){
                    if(err || body.code)
                        return res.render('admin/error', {msg: "链接服务器失败", docs: {
                            jssdk: wechat.getJSSDK(req.originalUrl)
                        }});
                    else
                        res.redirect(wechat.config.URL+"open/merchant_admin_create?status=true&token="+token);
                });

            };
        });
    }else if(status && token && !errcode){
        var SEND = new send(0);
        SEND.msg = "您被邀请为本酒店的管理员";
        SEND.docs = {
            token : token,
            button : "确定",
            buttonFun : function(){
                var form = $('<form method="post" style="display: none;"><input name="token" /></form>').appendTo("body");
                form.find('input').val(token);
                form.submit();
            },
            jssdk : wechat.getJSSDK(req.originalUrl)

        };
        res.render('open/info', SEND);
    };
};

var POST = function(req, res, next){
    var body = req.body;
    var token = body.token;
    var tag_id = [wechat.config.tagid_contrast[2], wechat.config.tagid_contrast[3]];
    var oid, ooid, mid, merchant;
    var tokenType = "TempToken";
    var template = "admin/success";
    var SEND;

    var getToken = function(){
        var that = this;
        core.api("open/getToken", {type: tokenType, token: token}, function(err, doc){
            that.step({err: err, doc: doc});
        });
    };

    var getTokenEnd = function(result){
        var err = result.err;
        var doc = result.doc;
        var that = this;
        if(err){
            SEND = new send(300000);
            template = "admin/error";
            return that.end();
        };
        if(doc.code){
            SEND = doc;
            template = "admin/error";
            return that.end();
        }

        doc = doc.docs;
        console.log(doc,'====');
        doc.data = JSON.parse(doc.data);
        oid = doc.data.oid;
        ooid = doc.data.ooid;
        mid = doc.data.mid;

        core.api("open/deleteToken", {token: token, type : tokenType});
        return true;
    };

    var findMerchant = function(){
        var that = this;
        var params = {
            "mid" :  mid
        };
        core.api("merchant/find", params, function(err, doc){
            that.step({err: err, doc: doc});
        });
    };

    var findMerchantEnd = function(result){
        var err = result.err;
        var doc = result.doc;
        var that = this;
        if(err){
            SEND = new send(300000);
            template = "admin/error";
            return that.end();
        };
        if(doc.code){
            SEND = doc;
            template = "admin/error";
            return that.end();
        };

        merchant = doc.docs;

        if(merchant.admin){
            SEND = new send(300005);
            template = "open/info";
            return that.end();
        }

        return true;

    };

    var upMerchant = function(){
        var that = this;
        var params = {
            mid : mid,
            update : JSON.stringify({
                admin : oid,
                $push: {
                    personnel : {
                        openid : oid,
                        level : 0,
                        recommend : ooid
                    }
                }
            })
        };
        core.api("merchant/update", params, function(err, doc){
            that.step({err: err, doc: doc});
        });
    };

    var upMerchantEnd = function(result){
        var err = result.err;
        var doc = result.doc;
        var that = this;
        if(err){
            SEND = new send(300000);
            template = "admin/error";
            return that.end();
        };
        if(doc.code){
            SEND = doc;
            template = "admin/error";
            return that.end();
        };

        return true;
    };

    // var getUser = function(){
    //     var that = this;
    //     var params = {
    //         openid: oid,
    //         tagid_list: tag_id
    //     };
    //     core.api("user/getUser",params, function(err, doc){
    //         that.step({err: err, doc: doc});
    //     });
    // };
    //
    // var getUserEnd = function(result){
    //     var err = result.err;
    //     var doc = result.doc;
    //     var that = this;
    //     if(err){
    //         SEND = new send(300000);
    //         return that.end();
    //     };
    //
    //     if(doc.code && doc.code !== 100201){
    //         SEND = doc;
    //         return that.end();
    //     };
    //     if(doc.docs){
    //         return that.step(true);
    //     };
    //
    //     if(doc.code === 100201)
    //         return that.step(false);
    // };
    //
    // var upUser = function(tag){
    //     var that = this;
    //     var update = {
    //         $addToSet: {
    //             merchant: parseInt(mid)
    //         }
    //     };
    //
    //     if(!tag){
    //         var params = {
    //             url : "members/batchtagging",
    //             openid_list : [oid],
    //             tagid : tag_id[]
    //         };
    //         wechat.api.list.user.tags(params);
    //     };
    //
    //     update.$addToSet.tagid_list = parseInt(tag_id);
    //
    //     var params = {
    //         openid: oid,
    //         update: JSON.stringify(update)
    //     };
    //
    //     core.api("user/upUser", params, function(err, doc){
    //         that.step({err: err, doc: doc});
    //     });
    // };

    var getUser = function(){
        var that = this;
        var params = {
            openid: oid,
            $or: JSON.stringify([{tagid_list: tag_id[0]}, {tagid_list: tag_id[1]}])
        };

        core.api("user/getUser", params, function(err, doc){
            return that.step({err: err, doc: doc});
        });
    }

    var getUserEnd = function(result){
        var err = result.err;
        var doc = result.doc;
        var that = this;
        if(err){
            SEND = new send(300000);
            template = "admin/error";
            return that.end();
        };
        if(doc.code && doc.code !== 100201){
            SEND = doc;
            template = "admin/error";
            return that.end();
        }
        if(doc.code === 100201){
            var params = [{
                url : "members/batchtagging",
                openid_list : [oid],
                tagid : tag_id[0]
            },params = {
                url : "members/batchtagging",
                openid_list : [oid],
                tagid : tag_id[1]
            }];
            wechat.api.list.user.tags(params[0], function(err, doc){
                wechat.api.list.user.tags(params[1]);
            });
            return that.step(tag_id);

        }else{
            user = doc.docs;
            var nulltagid = null;
            var newtagid = {};
            for(var x = 0; x < tag_id.length; x++){
                newtagid[tag_id[x]] = true;
            }
            for(var x = 0; x < tag_id.length; x++){
                var thistag = false;
                for(var y = 0; y < user.tagid_list.length; y++){
                    if(user.tagid_list[y] == tag_id[x])
                        delete newtagid[tag_id[x]];
                }
            };

            for(var i in newtagid)
                nulltagid = parseInt(i);

            if(!nulltagid)
                return that.step(null);

            var params = {
                url : "members/batchtagging",
                openid_list : [body.admin],
                tagid : nulltagid
            };
            wechat.api.list.user.tags(params);

            return that.step([nulltagid]);
        }
    };

    var upUser = function(result){
        var that = this;
        var openid = oid;
        var update = {
            $addToSet: {
                merchant: parseInt(merchant.mid)
            }
        };
        if(result != null){
            update.$addToSet.tagid_list = {
                $each : result
            };
        }

        var params = {
            openid : openid,
            update : JSON.stringify(update)
        };
        core.api("user/upUser", params, function(err, doc){
            return that.step({err: err, doc: doc});
        });
    };

    var upUserEnd = function(result){
        var err = result.err;
        var doc = result.doc;
        var that = this;
        if(err){
            SEND = new send(300000);
            template = "admin/error";
            return that.end();
        };

        if(doc.code){
            SEND = doc;
            template = "admin/error";
            return that.end();
        };

        return true;
    };

    var end = function(){
        // if(SEND && SEND.code){
            // console.log(SEND,'=====================!!!');
            // req.error = SEND;
            // return next();
        if(!SEND){
            SEND = new send(0);
            SEND.msg = "恭喜您已经成为本店管理员！";
            // SEND.docs = {
            //     jssdk : wechat.getJSSDK(req.originalUrl)
            // };
        };

        SEND.docs = SEND.docs || {};
        SEND.docs.jssdk = wechat.getJSSDK(req.originalUrl);

        res.render(template, SEND);
    }

    step.Step(
        getToken,
        getTokenEnd,
        findMerchant,
        findMerchantEnd,
        upMerchant,
        upMerchantEnd,
        getUser,
        getUserEnd,
        upUser,
        upUserEnd,
        end
    );

};


exports.GET = GET;
exports.POST = POST;
